<script setup lang="ts">
import { getActivityDetailApi, deleteActivityDataApi, deleteActivityCommentDataApi, getActivityCommentApi, createActivityCommentDataApi } from "@@/apis/activity"
import { ChatLineRound, PictureFilled } from "@element-plus/icons-vue"
import { onMounted, ref } from "vue"
import { formatDateTime } from "@/common/utils/datetime.ts"
import SingleImageUpload from "./SingleImageUpload.vue"
import { getToken } from "@@/utils/cache/cookies"

defineOptions({
  name: "Detail",
  inheritAttrs: false
})

const router = useRouter()
const route = useRoute()
const detailData = ref({})
const commentData = ref([])
const formRef = ref(null)
const formData = ref({
  content: '',
  image: ''
})
const formRules = {
  content: [{ required: true, trigger: "blur", message: "请输入评论" }]
}
const openComment = ref(false)

function editActivity() {
  const id = route.query.id
  router.push({
    path: "/activity/operate",
    query: { id }
  })
}

function handleQuery() {
  const params = {
    activity_id: route.query.id
  }
  getActivityDetailApi(params).then((res) => {
    if (res.data) {
      detailData.value = res.data
      updateDocumentTitle(res.data.title)
      getActiveComment()
    }
  })
}

function deleteActivity() {
  ElMessageBox.confirm(`正在删除本次活动，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteActivityDataApi(route.query.id).then(() => {
      ElMessage.success("删除成功")
      router.push({
        path: "/activity/list"
      })
    })
  })
}

function reviewComments() {
  router.push({
    path: "/activity/review",
    query: { id: route.query.id }
  })
}

function getActiveComment() {
  getActivityCommentApi({
    type: 2,
    page: 1,
    page_size: 1000,
    activity_id: route.query.id
  }).then(({ data }) => {
    commentData.value = data.list
  }).catch(() => {
    commentData.value = []
  }).finally(() => {
    // loading.value = false
  })
}

function delComment(row) {
  ElMessageBox.confirm(`正在删除评论，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteActivityCommentDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      handleQuery()
    })
  })
}

function cancelComment() {
  openComment.value = false
  formData.content = ''
  formData.image = ''
  formRef.value?.resetFields()
}

function onSubmit() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("请输入评论内容！")
      return
    }

    const token = getToken()
    const params = {
      token,
      activity_id: route.query.id,
      content: formData.value.content,
      file_json: formData.value.image === '' ? [] : JSON.stringify([{'type':'image','url': formData.value.image}]),
      comment_id: [],
      status: '',
      type: 2
    }
    createActivityCommentDataApi(params).then(({ data }) => {
      ElMessage.success("评论成功")
      getActiveComment()
      cancelComment()
    }).catch(() => {

    }).finally(() => {
      // loading.value = false
    })
  })
}

function formatJson(data) {
  if (data !== '') {
    const row = JSON.parse(data)
    return row[0].url
  }
}

const updateDocumentTitle = (newTitle) => {
  document.title = newTitle;
}
onMounted(() => {
  handleQuery()
})
</script>

<template>
  <div class="app-main">
    <div class="card-header">
      <span>{{ detailData.title }}</span>
    </div>
      <div class="card-body">
        <el-text>
          <div v-html="detailData.content" />
          <!-- {{ detailData.content }} -->
        </el-text>
      </div>

        <div class="footer-main">
          <div class="comment-title">
            <span>
              {{ commentData.length }}条评论
            </span>
            <el-button v-if="!openComment" type="primary" :icon="ChatLineRound" link @click="openComment = true">
              我要评论
            </el-button>
          </div>
          <div class="comment-body" v-if="openComment">
            <el-form ref="formRef" :model="formData" :rules="formRules">
              <el-form-item prop="content">
                <el-input v-model="formData.content" placeholder="请输入评论" clearable />
              </el-form-item>
              <div class="show-img">
                <SingleImageUpload v-model="formData.image" v-if="formData.image" />
              </div>
            </el-form>
            <div class="comment-more">
              <div v-if="formData.image" />
              <div class="update-img" v-if="!formData.image">
                <SvgIcon name="updateImg" class="svg-icon" />
                <div class="update-button">
                  <SingleImageUpload v-model="formData.image" />
                </div>
              </div>
              <div>
                <el-button type="warning" @click="cancelComment">取消评论</el-button>
                <el-button type="primary" @click="onSubmit">发布评论</el-button>
              </div>
            </div>

          </div>
          <div class="comment-item" v-for="(item, index) in commentData" :key="index">
            <div class="user-img">
              <el-icon v-if="!item.image || item.image === ''"><UserFilled /></el-icon>
              <el-image v-else style="width: 20px; height: 20px" :src="item.image" fit="fill" />
            </div>
            <div class="comment-box">
              <div class="comment-item-head">
                <div class="user-name">匿名用户 {{ index + 1 }}：</div>
                <div class="comment-del">
                  <!-- <el-button type="danger" link>
                    删除
                  </el-button> -->
                </div>
              </div>
              <div class="comment-item-body">
                <div v-if="item.file_json">
                  <el-image  :src="formatJson(item.file_json)" fit="fill" />
                </div>
                <div>
                  {{ item.content }}
                </div>
              </div>
              <div class="comment-item-footer">
                <div class="attribute">
                  <el-text type="info" class="mr-5">{{ formatDateTime(item.createtime * 1000) }}</el-text>
                  <!-- <el-text type="info">IP</el-text> -->
                </div>

                <!-- <div class="operate">
                  <el-button type="info" :icon="ChatLineRound" link>
                    回复
                  </el-button>
                  <el-button type="danger" link @click="delComment(item)">
                    删除
                  </el-button>
                </div> -->
              </div>
            </div>
          </div>
        </div>

  </div>
</template>

<style lang="scss" scoped>
.header-operate {
  padding-top: 15px;
  .operate-main {
    display: flex;
    .foot-operate {
      flex: 1;
      margin-right: 15px;
    }
  }
}
.app-main {
  min-height: 580px;
  padding: 5px;
  background-color: #ffffff;
  .card-header {
    padding: 10px;
  }
  .card-body {
    min-height: 50px;
    border-top: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
  }
}
.footer-main {
  .comment-title {
    padding: 15px;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .comment-body {
    border: 1px solid #eeeeee;
    padding: 5px;
    .show-img {
      display: flex;
    }
    .comment-more {
      // border-top: 1px solid #eeeeee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-radius: 5px;
      .update-img {
        width: 40px;
        height: 40px;
        font-size: 20px;
        position: relative;
        overflow: hidden;
        text-align: center;
        .update-button {
          opacity: 0;
          position: absolute;
          left: -45%;
          top: -45%
        }
      }
    }
  }
  .comment-item {
    padding: 15px 0;
    display: flex;
    .user-img {
      width: 20px;
      text-align: center;
    }
    .comment-box {
      flex: 1;
      padding-left: 10px;
      padding-right: 30px;
      .comment-item-head {
        display: flex;
        .user-name {
          flex: 1;
        }
        .comment-del {

        }
      }
      .comment-item-body {
        padding: 10px 0;
      }
      .comment-item-footer {
        display: flex;
        justify-content: space-between;
        .attribute {
          display: flex;
        }
        .operate {
          display: flex;
        }
      }
    }
  }
}
</style>
